package com.bootlever.framework.core.configuration;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.bootlever.framework.core.properties.BasicProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.List;

@Configuration
@ConditionalOnExpression("'${bootlever.framework.base.jsonParser.name:fastjson}'=='fastjson'")
public class FastJsonConfiguration extends WebMvcConfigurerAdapter{
    private static final Logger logger = LoggerFactory.getLogger(FastJsonConfiguration.class);

    @Autowired
    private BasicProperties basicProperties;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
        logger.info("使用fastjson作为json转换器");
        //fastJson covert
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //返回内容的过滤，选择常用的几种来配置
        List<SerializerFeature> features = basicProperties.getJsonParser().getFeatures();
        if (features != null && features.size() > 0) {
            if (logger.isInfoEnabled()) {
                logger.info("FastJson启用的内容过滤器：{}", JSON.toJSONString(features));
            }
            fastJsonConfig.setSerializerFeatures(features.toArray(new SerializerFeature[features.size()]));
        }
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
}
